package com.foreveross.crawl.adapter;

import java.text.ParseException;
import java.util.Date;

import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.foreveross.crawl.common.util.RegHtmlUtil;
import com.foreveross.crawl.common.util.StringUtils;
import com.foreveross.taskservice.common.bean.TaskModel;

/**
 * 抓取适配器简单工厂
 * 
 * @author xiangsf
 * @since 2013-1-31
 */
public class CrawlAdapterFactory {

	protected static Logger logger = LoggerFactory.getLogger(CrawlAdapterFactory.class);

	/**
	 * 根据获取的渠道标识获得适配器实例
	 * <p>
	 * 目前无法从queue对象上获得渠道标识, 以后采用类反射
	 * 
	 * @param channelId
	 * @param queue
	 * @return
	 */

	public static AbstractAviationAdapter buildAdaptor(final TaskModel queue) {
		AbstractAviationAdapter adapter = null;
		try {
			adapter = AdapterManager.getInstance().buildAdapter(queue.getGrabChannelId(), queue);
		} catch (Exception e) {
			adapter = new DefaultAdapter(queue);
		}
		return adapter;
	}

	/**
	 * 得到起飞/gcj dp 时间
	 * <p>
	 * 由flightBatchDate+flightBatchStartTime组合而成
	 * 
	 * @return
	 * @throws ParseException
	 * @throws java.text.ParseException
	 */
	public static Date getFlightTime(String flightBatchDate, String timez) {
		if (StringUtils.isNotEmpty(flightBatchDate) && StringUtils.isNotEmpty(timez)) {
			// 引处replaceAll(" ", "")替换的不是空格，请不要去掉，后面有处理空格
			timez = timez.trim().replaceAll("^\\W+|\\W+$| ", "");
			String day = "0";// 跨天
			try {
				String time = timez.indexOf(":") > -1 ? timez.replace(":", "") : timez;
				if (time.length() < 4) {
					time = "0" + time;
				}
				if (RegHtmlUtil.regMathcher(time, "[+-]\\d{1,2}?$")) {
					day = RegHtmlUtil.regStr(time, "(.*?)([+-]\\d{1,2}?)$", 2);
					time = RegHtmlUtil.regStr(time, "(.*?)[+-](\\d{1,2}?)$", 1);
				}
				
				if (time.length() == 3) time = "0" + time;
				else if (time.length() == 2) time = "00" + time;
				else if (time.length() == 1) time = "000" + time;
				Date date;
				if (time.matches("\\w{2,4}?-\\w{1,2}-?.*?")) {
					date = DateUtils.parseDate(time, "yyyy-MM-dd HHmm");
				} else {
					date = DateUtils.parseDate(flightBatchDate + " " + time, "yyyy-MM-dd HHmm");
				}
				if (day.contains("+")) {
					int intday = Integer.parseInt(StringUtils.trim(day.replace("+", "")));
					date = DateUtils.addDays(date, intday);
				} else if (day.contains("-")) {
					int intday = Integer.parseInt(StringUtils.trim(day.replace("-", "")));
					date = DateUtils.addDays(date, -intday);
				}
				return date;
			} catch (java.text.ParseException e) {
				logger.error(e.getMessage());
			}
		}
		return null;
	}
 
}
